package com.mrjy.maintain.bo;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.mrjy.common.entity.DistributorInfo;
import com.mrjy.common.entity.MingrenTeamInfo;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.util.DateUtil;
import com.mrjy.common.util.ExcelUtil;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.common.util.UpdateDisableFlagUtil;
import com.mrjy.maintain.dao.IMingrenTeamInfoDao;
import com.mrjy.maintain.dao.IUserInfoDao;
import com.mrjy.maintain.dto.MingrenTeamInfoDTO;
import com.mrjy.share.dao.IDistributorInfoDao;
import com.mrjy.share.dao.IDistributorTeamInfoDao;
import com.mrjy.share.dto.DistributorInfoDTO;

@Service("mingrenTeamInfoBo")
public class MingrenTeamInfoBo implements IMingrenTeamInfoBo{

	@Resource
	private IMingrenTeamInfoDao mingrenTeamInfoDao;	
	@Resource
	private IDistributorInfoDao distributorInfoDao;
	@Resource
	private IDistributorTeamInfoDao distributorTeamInfoDao;
	@Resource
	private IUserInfoDao userInfoDao;

	@Override
	public Object txInsert(MingrenTeamInfoDTO info) {
		Map<String,Object> map = new HashMap<String,Object>();
		if(StringUtils.isBlank(info.getMobilePhone())){
			map.put("err_code", 201);
			map.put("err_msg", "手机号码为空");
			return map;
		}
		//根据手机号查询该用户是否已经是家人
		UserInfo userInfo1 = userInfoDao.queryByMobilePhoneExist(info.getMobilePhone());
		if(userInfo1 != null){//该用户已经是家人
			map.put("err_code", 2);
			map.put("err_msg", "该用户已经是家人");
		}else{
			UserInfo userInfo = userInfoDao.queryByMobilePhone(info.getMobilePhone());
			int count = 0;
			if(userInfo != null  ){
				userInfo.setUserName(info.getUserName());
				if(StringUtils.isBlank(userInfo.getRecommendCode())){
					userInfo.setRecommendCode(userInfoDao.generateRecommendCodeOne(8));
				}
				userInfo.setMobilePhone(info.getMobilePhone());
				userInfo.setBankCard(info.getBankCard());
				userInfo.setIdCard(info.getIdCard());
				count = userInfoDao.updateById(userInfo);
				
			}else {
				userInfo = new UserInfo();
				userInfo.setUserName(info.getUserName());
				userInfo.setMobilePhone(info.getMobilePhone());
				userInfo.setBankCard(info.getBankCard());
				userInfo.setIdCard(info.getIdCard());
				userInfo.setRegisterDate(new Date().getTime());
				userInfo.setDisableFlag(0);
				userInfo.setRecommendCode(userInfoDao.generateRecommendCodeOne(8));
				
				count = userInfoDao.insert(userInfo);
			}
			
			//插入分类标签记录
			if (count == 1) {
				//添加MingrenTeamInfo
				MingrenTeamInfo mrti = new MingrenTeamInfo();
				mrti.setUserId(userInfo.getId());
				mrti.setSharingProportion(info.getSharingProportion());
				mrti.setCreateTime(new Timestamp(System.currentTimeMillis()));
				mrti.setDisableFlag(0);
				mingrenTeamInfoDao.insert(mrti);
				
				//新增一条为员工身份的推广者记录
				DistributorInfo dInfo = new DistributorInfo();
				dInfo.setUserId(userInfo.getId());
				dInfo.setDistributorName(userInfo.getUserName());
				dInfo.setMobilePhone(userInfo.getMobilePhone());
				dInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
				dInfo.setShareCode(userInfo.getRecommendCode());
				dInfo.setDistributorType("7");//家人
				
				dInfo.setSharingProportion(info.getSharingProportion());
				dInfo.setDisabledFlag(0);
				
				distributorInfoDao.insert(dInfo);
				
				map.put("err_code", 0);
				map.put("err_msg", "插入成功");
			}else{
				map.put("err_code", 1);
				map.put("err_msg", "插入失败");
			}
		}
		return map;
	}

	@Override
	public int txDeleteByIds(int[] ids) {
		return mingrenTeamInfoDao.deleteByIds(ids);
	}

	@Override
	public Object txUpdateById(MingrenTeamInfoDTO info) {
		Map<String,Object> map = new HashMap<String,Object>();
		if(StringUtils.isBlank(info.getMobilePhone())){
			map.put("err_code", 201);
			map.put("err_msg", "手机号码为空");
			return map;
		}
		//更新MingrenTeamInfo
		MingrenTeamInfo mrti = new MingrenTeamInfo();
		mrti.setId(info.getId());
		mrti.setSharingProportion(info.getSharingProportion());
		int count = mingrenTeamInfoDao.updateById(mrti);
		
		UserInfo userInfo = userInfoDao.queryById(info.getUserId());
		if(userInfo != null  ){
			userInfo.setUserName(info.getUserName());
			userInfo.setBankCard(info.getBankCard());
			userInfo.setIdCard(info.getIdCard());
			userInfo.setMobilePhone(info.getMobilePhone());
			userInfoDao.updateById(userInfo);
		}
		
		//插入分类标签记录
		if (count == 1) {
			//更新推广者表
			Map<String,Object> paramMap = new HashMap<String,Object>();
			paramMap.put("userId", info.getUserId());
			paramMap.put("disabledFlag", 0);
			paramMap.put("distributorTypes", new String[]{"7"});
			List<DistributorInfoDTO> dInfoList = distributorInfoDao.queryByMap(paramMap);
			if(dInfoList != null && dInfoList.size() > 0){
				DistributorInfo dInfo = new DistributorInfo(); 
				dInfo.setId(dInfoList.get(0).getId());
				dInfo.setMobilePhone(info.getMobilePhone());
				dInfo.setDistributorName(info.getUserName());
				dInfo.setSharingProportion(info.getSharingProportion());
				distributorInfoDao.updateById(dInfo);
			}
			
			map.put("err_code", 0);
			map.put("err_msg", "更新成功");
		}else{
			map.put("err_code", 1);
			map.put("err_msg", "更新失败");
		}	
		return map;
	}

	@Override
	public MingrenTeamInfoDTO queryById(int id) {
		return mingrenTeamInfoDao.queryById(id);
	}

	@Override
	public Object queryPage(MingrenTeamInfoDTO dto) {
		Map<String,Object> map = new HashMap<String,Object>();
		//乱码处理
		int total = mingrenTeamInfoDao.querySumMingrenTeamInfo(dto);
		if(total > 0){
			List<MingrenTeamInfoDTO> list = mingrenTeamInfoDao.queryPage(dto);
			if(null != list && list.size() > 0){
				map.put("err_code", 0);
				map.put("err_msg", "查询成功");
				map.put("rows", list);
				map.put("total", total);
			}else {
				map.put("err_code", 1);
				map.put("err_msg", "无数据");
				map.put("rows", list);
				map.put("total", 0);
			}
		}else{
			map.put("err_code", 2);
			map.put("err_msg", "无数据");
			map.put("rows", null);
			map.put("total", 0);
		}
		
		return map;
	}

	@Override
	public Object txUpdateDisableFlag(MingrenTeamInfo info) {
		Map<String,Object> map = new HashMap<String,Object>();
		int row = 0;
		if(info == null){
			row = -1;
			return row;
		}
		if(info.getIds() != null){
			String[] distributorTypes = {"7"};
			MingrenTeamInfoDTO mti = null;
			for(int i =0; i<info.getIds().length; i++){
				mti = mingrenTeamInfoDao.queryById(info.getIds()[i]);
				if(mti !=null){
					//操作推广信息
					UpdateDisableFlagUtil.updateDisableFlagForTeam(distributorTypes,
							mti.getUserId(), info.getDisableFlag());
				}
			}
		}
		row = mingrenTeamInfoDao.updateDisableFlag(info);
		if(row > 0){
			map.put("err_code", 0);
			map.put("err_msg", "操作成功");
			map.put("rows", row);
				
		}else{
			map.put("err_code", 1);
			map.put("err_msg", "操作失败");
		}
		return map;
	}

	@Override
	public Object queryByUserId(MingrenTeamInfoDTO info) {
		Map<String,Object> map = new HashMap<String,Object>();
		List<MingrenTeamInfoDTO> list = mingrenTeamInfoDao.queryByUserId(info);
		if(null != list && list.size() > 0){
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("rows", list);
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "无数据");
			map.put("rows", list);
			map.put("total", 0);
		}
		return map;
	}

	@Override
	public Object exportExl(MingrenTeamInfoDTO dto, HttpServletResponse response,
			HttpSession session) {
		Map<String,Object> map = new HashMap<String,Object>();
		// TODO Auto-generated method stub
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		List<MingrenTeamInfoDTO> familyData = mingrenTeamInfoDao.queryPage(dto);
		if (familyData == null || familyData.size()==0) {
			map.put("err_code", 404);
			map.put("err_msg", "无可导出数据");	
			return map;
		}else{
			try {
				ExcelUtil.writeExcel(response, "家人"+DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)+".xls", familyData, MingrenTeamInfoDTO.class);
				map.put("err_code", 200);
				map.put("err_msg", "导出成功");
			} catch (Exception e) {
				e.printStackTrace();
				map.put("err_code", 500);
				map.put("err_msg", "导出失败");
			}
		}
		return map;
	}

	

	
	
}
